<template>
  <view class="app-container ver-layout">
    <!-- 上传照片   -->
    <view class="photo-layout hor-layout-center" @click="uploadImage">
      <view class="photo-view ver-layout-center-all">
        <u-icon v-if="!form.picture_path" name="camera" color="#999999" size="50"></u-icon>
        <image v-else :src="form.picture_path" class="photo-image"/>
      </view>
      <view class="upload-view">上传封面图片</view>
    </view>
    <!--  信息填写  -->
    <u-form :model="form" ref="uForm" label-width="97px" :label-style="formLabel">
      <u-form-item label="课程标题">
        <u-input v-model="form.title" placeholder="请输入课程标题" :maxlength="10"/>
      </u-form-item>
      <u-form-item label="课程类别">
        <view class="form-select-item hor-layout-center" @click="form.showCate=true">
          <view class="form-select-text">{{ form.cateObj.label ? form.cateObj.label : '请选择' }}</view>
          <u-icon name="arrow-right" color="#000000"></u-icon>
        </view>
        <u-select v-model="form.showCate" :list="cateList" title="选择课程类别"
                  :default-value="form.cateObj.value" @confirm="confirmSelectCate"></u-select>
      </u-form-item>
      <u-form-item label="关联专业">
        <view class="form-select-item hor-layout-center" @click="form.showMajor=true">
          <view class="form-select-text">{{ form.majorObj.label ? form.majorObj.label : '请选择' }}</view>
          <u-icon name="arrow-right" color="#000000"></u-icon>
        </view>
        <u-select v-model="form.showMajor" :list="majorList" title="选择关联专业"
                  :default-value="form.majorObj.value" @confirm="confirmSelectMajor"></u-select>
      </u-form-item>
      <u-form-item label="授课方式">
        <u-radio-group v-model="form.typeName" @change="changeTypeClick">
          <u-radio v-for="(item, index) in studyTypes" :key="index" :name="item.name" active-color="#42B4AB">
            {{ item.name }}
          </u-radio>
        </u-radio-group>
      </u-form-item>
      <u-form-item label="上课方式">
        <u-radio-group v-model="form.modeName" @change="changeModeClick">
          <u-radio v-for="(item, index) in  studyModes" :key="index" :name="item.name" active-color="#42B4AB">
            {{ item.name }}
          </u-radio>
        </u-radio-group>
      </u-form-item>
      <u-form-item label="课程简介">
        <u-input v-model="form.description" type="textarea" border/>
      </u-form-item>
      <u-form-item label="是否上架">
        <u-switch v-model="statusChecked" active-color="#42B4AB" size="35"></u-switch>
      </u-form-item>
    </u-form>
    <!--  下一步  -->
    <view class="next-btn" @click="toChargeStandard">下一步</view>
  </view>
</template>

<script>
import EditStuInfo from "../enter/createClass/inputClassStu";
import {addChargeStand} from "@/router.js"
import {AddCourseApi} from "@/api/courseList.js"
import uploadFile from '@/common/ossutil/uploadFile.js'

let engine = new AddCourseApi()
export default {
  name: "addCourse",
  components: {EditStuInfo},
  data() {
    return {
      formLabel: {
        color: "#282828",
        fontSize: '15px',
        textAlign: 'justify',
        textAlignLast: 'justify',
        display: 'inline-block',
        paddingRight: '27px'
      },
      form: {
        picture_path: '',
        picture: '111',
        title: '',
        cate_id: '',
        cateObj: {},
        showCate: false,
        major: '',
        majorObj: {},
        showMajor: false,
        description: '',
        status: 1,//0否1是
        type: 1,
        typeName: '线上',
        mode: 1,
        modeName: '一对一',
      },
      statusChecked: true,//0否1是
      cateList: [],
      majorList: [],
      studyTypes: [{name: '线上', value: 1}, {name: '线下', value: 2}],//授课方式
      studyModes: [{name: '一对一', value: 1}, {name: '集体课', value: 2}],//上课方式
      courseObj: {},
    }
  },
  watch: {
    statusChecked(val) {
      this.form.status = val ? 1 : 0
    }
  },
  onLoad(options) {
    this.courseObj = options
    if (options.id) uni.setNavigationBarTitle({title: '修改课程'})
    this.getCourseDetail()
  },
  methods: {
    getCourseDetail() {
      //先获取到【专业列表接口】和【课程分类列表接口】后，再获取课程详情接口数据（另一种实现方式就是监听majorList和cateList数据，然后请求详情接口）
      Promise.all([this.getMajorList(), this.getCourseCateList()]).then(res => {
        console.log("getCourseDetail===", res)
        let {id} = this.courseObj
        if (!id) return
        engine.getCourseDetail(id).then(res => {
          let {mode, type, status, cate_id, major} = res.data
          let statusChecked = status === 1,
              cateObj = this.cateList.find(c => c.value === cate_id),
              majorObj = this.majorList.find(m => m.value === major),
              modeName = this.studyModes.find(m => m.value === mode).name,
              typeName = this.studyTypes.find(m => m.value === type).name
          if (cateObj) cateObj.value = [cateObj.value] //这里u-select控件需要的是一个数组，所以进行转换一下
          if (majorObj) majorObj.value = [majorObj.value]
          this.form = {...this.form, ...res.data, cateObj, majorObj, modeName, typeName,}
          this.statusChecked = statusChecked
        })
      })
    },
    getMajorList() {
      return new Promise((resolve, reject) => {
        engine.getMajorList().then(res => {
          this.majorList = res.data.map(item => {
            return {label: item.name, value: item.id}
          })
          resolve(res)
        }).catch(err => reject(err))//有一个接口报错下面的详情接口将不执行
      })
    },
    getCourseCateList() {
      return new Promise((resolve, reject) => {
        engine.getCourseCateList().then(res => {
          this.cateList = res.data.map(item => {
            return {label: item.title, value: item.id}
          })
          resolve(res)
        }).catch(err => reject(err))
      })
    },
    confirmSelectCate(e) {
      let channelIndex = this.cateList.findIndex(item => item.value === e[0].value)
      this.form.cateObj.value = [channelIndex]
      this.form.cateObj.label = e[0].label
      this.form.cate_id = e[0].value
    },
    confirmSelectMajor(e) {
      let channelIndex = this.majorList.findIndex(item => item.value === e[0].value)
      this.form.majorObj.value = [channelIndex]
      this.form.majorObj.label = e[0].label
      this.form.major = e[0].value
    },
    // 选中任一radio时，由radio-group触发
    changeModeClick(e) {
      this.form.mode = this.studyModes.find(s => s.name === e).value
    },
    changeTypeClick(e) {
      this.form.type = this.studyTypes.find(s => s.name === e).value
    },
    toChargeStandard() {
      this.$u.route({url: addChargeStand, params: {course: JSON.stringify(this.form)}})
    },
    uploadImage() {
      uni.chooseImage({count: 1}).then(res => {
        let path = res[1].tempFilePaths[0],
            file = res[1].tempFiles[0]
        uploadFile(path, file, (f_name, r_path) => {
          console.log("uploadFile", f_name, r_path)
          this.form.picture_path = r_path
          this.saveImg(f_name)
        }, (err) => {
          this.$u.toast("上传错误！")
          console.error("uploadFile", err)
        })
      })
    },
    saveImg(path) {
      engine.saveResource(path).then(res => {
        this.form.picture = res.data[0];
      }).catch(err => this.$u.toast(err.message))
    }
  }
}
</script>

<style scoped>
page {
  background: #FFFFFF;
}

.photo-layout {
  padding-bottom: 12px;
  border-bottom: 1px solid #E5E5E5;
}

.photo-view {
  width: 59px;
  height: 73px;
  background: #D1D1D1;
}

.photo-image {
  width: 100%;
  height: 100%
}

.upload-view {
  margin-left: 25px;
  font-size: 15px;
  color: #333333;
  font-family: Source Han Sans CN;
}

.form-select-item {
  width: 100%;
}

.form-select-text {
  flex: 1;
  width: 0;
  margin-right: 3px;
  text-align: right;
  font-size: 15px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #000000;
}

.next-btn {
  position: fixed;
  bottom: 10px;
  left: 26px;
  height: 40px;
  width: calc(100% - 26 * 2px);
  background: #42B4AB;
  border-radius: 40px;
  text-align: center;
  line-height: 40px;
  /* 文本样式 */
  font-size: 16px;
  font-family: Source Han Sans CN;
  font-weight: bold;
  color: #FFFFFF;
}
</style>
